package com.leo.util;

import java.lang.reflect.Method;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletRequest;


public class BeanSetter{
	public static <T> void getBean(ServletRequest request, T bean) throws Exception{
		getBean(request,bean.getClass(),bean);
	}
	
	
	public static Object getBean(ServletRequest request, Class beanClass) throws Exception{
		Object bean = beanClass.newInstance();
		getBean(request, beanClass, bean);
		return bean;
	}
	

	private static <T> void getBean(ServletRequest request, Class beanClass, Object bean) throws Exception{
		Pattern pattern = Pattern.compile("^set([A-Z])(.*)");
		Method[] methods = beanClass.getMethods();
		for(Method method: methods){
			Matcher matcher = pattern.matcher(method.getName());
			if(!matcher.matches()){
				continue;
			}
		 String name = matcher.group(1).toLowerCase() + matcher.group(2);
			Object param = request.getParameter(name);
			method.invoke(bean, param);
		}
	}

}
